package com.qq.mobilemanager.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.qq.mobilesafe.R;
import com.qq.mobilesafe.base.adapter.ViewHolder;
import com.qq.mobilesafe.base.adapter.abslistview.CommonAdapter;
import com.qq.mobilesafe.domain.ContactInfo2;
import com.qq.mobilesafe.engine.ContactInfoParser2;
import com.qq.mobilesafe.utils.PinyinUtils;
import com.qq.mobilesafe.view.QuickIndexBar;
import com.qq.mobilesafe.view.QuickIndexBar.OnLetterUpdateListener;
import com.qq.mobilesafe.view.SearchEditText;

public class ContactActivity extends Activity implements OnItemClickListener {

	@ViewInject(R.id.lv_contact)
	private ListView lv_contact;

	// private ArrayList<HashMap<String, String>> list;

	private List<ContactInfo2> list2;

	@ViewInject(R.id.tv_center)
	private TextView tv_center;

	@ViewInject(R.id.bar)
	private QuickIndexBar bar;

	@ViewInject(R.id.et_search)
	private SearchEditText et_search;

	private Handler mHandler = new Handler();

	private ContactAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_contact);
		ViewUtils.inject(this);
		// list = readContact();
		// lv_contact.setAdapter(new SimpleAdapter(this, list,
		// R.layout.home_list_item, new String[] { "name", "phone" },
		// new int[] { R.id.tv_name, R.id.tv_phone }));
		//
		// lv_contact.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// String phone = list.get(position).get("phone");
		// Intent intent = new Intent();
		// intent.putExtra("phone", phone);
		// setResult(Activity.RESULT_OK, intent);
		// finish();
		// }
		// });
		// 设置监听
		bar.setListener(new OnLetterUpdateListener() {
			@Override
			public void onLetterUpdate(String letter) {
				// Utils.showToast(getApplicationContext(), letter);
				showLetter(letter);
				// 根据字母定位ListView, 找到集合中第一个以letter为拼音首字母的对象,得到索引
				for (int i = 0; i < list2.size(); i++) {
					ContactInfo2 person = list2.get(i);
					String l = person.pinyin.charAt(0) + "";
					if (TextUtils.equals(letter, l)) {
						// 匹配成功
						lv_contact.setSelection(i);
						break;
					}
				}
			}
		});
		list2 = ContactInfoParser2.findAll(this);
		// 排序
		Collections.sort(list2);
		adapter = new ContactAdapter(ContactActivity.this ,R.layout.item_contact , list2);
		lv_contact.setAdapter(adapter);
		lv_contact.setOnItemClickListener(this);

		// 根据输入框输入值的改变来过滤搜索
		et_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

	}

	// private ArrayList<HashMap<String, String>> readContact() {
	//
	// Uri rawContactsUri = Uri
	// .parse("content://com.android.contacts/raw_contacts");
	// Uri dataUri = Uri.parse("content://com.android.contacts/data");
	//
	// ArrayList<HashMap<String, String>> arrayList = new
	// ArrayList<HashMap<String, String>>();
	//
	// Cursor cursor = getContentResolver().query(rawContactsUri,
	// new String[] { "contact_id" }, null, null, null);
	//
	// if (cursor != null) {
	//
	// while (cursor.moveToNext()) {
	// String contactId = cursor.getString(0);
	//
	// Cursor dataCursor = getContentResolver().query(dataUri,
	// new String[] { "data1", "mimetype" }, "contact_id = ?",
	// new String[] { contactId }, null);
	// if (dataCursor != null) {
	// HashMap<String, String> map = new HashMap<String, String>();
	// while (dataCursor.moveToNext()) {
	// String data1 = dataCursor.getString(0);
	// String mimetype = dataCursor.getString(1);
	// if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
	// map.put("phone", data1);
	//
	// } else if ("vnd.android.cursor.item/name"
	// .equals(mimetype)) {
	// map.put("name", data1);
	// }
	// }
	// arrayList.add(map);
	//
	// dataCursor.close();
	// }
	// }
	// cursor.close();
	// }
	// return arrayList;
	//
	// }

	// private class ContactAllAdapter extends BaseAdapter {
	//
	// @Override
	// public int getCount() {
	// return list2.size();
	// }
	//
	// @Override
	// public Object getItem(int position) {
	// return list2.get(position);
	// }
	//
	// @Override
	// public long getItemId(int position) {
	// return position;
	// }
	//
	// @Override
	// public View getView(int position, View convertView, ViewGroup parent) {
	// ViewHolder holder;
	// if (convertView == null) {
	// holder = new ViewHolder();
	// convertView = View.inflate(ContactActivity.this,
	// R.layout.item_contact, null);
	// holder.icon = (ImageView) convertView.findViewById(R.id.icon);
	// holder.tv_name = (TextView) convertView
	// .findViewById(R.id.tv_name);
	// holder.tv_number = (TextView) convertView
	// .findViewById(R.id.tv_number);
	// convertView.setTag(holder);
	//
	// } else {
	// holder = (ViewHolder) convertView.getTag();
	// }
	// ContactInfo2 contactInfo = list2.get(position);
	// Bitmap bitmap = ContactInfoParser2.getBitmap(ContactActivity.this,
	// contactInfo.id);
	//
	// // 判断当前的bitmap 是否为null。如果为null。那么设置默认的图片
	// if (null == bitmap) {
	// holder.icon.setImageResource(R.drawable.contact2);
	// } else {
	// // 如果不为null。那么直接设置查询出来的图片
	// holder.icon.setImageBitmap(bitmap);
	// }
	// holder.tv_name.setText(contactInfo.name);
	// holder.tv_number.setText(contactInfo.phone);
	//
	// return convertView;
	// }
	//
	// }
	//
	// static class ViewHolder {
	// private TextView tv_name;
	// private TextView tv_number;
	// private ImageView icon;
	//
	// }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ContactInfo2 info = list2.get(position);
		// 获取到联系人的电话号码
		String phone = info.phone;
		Intent intent = new Intent();
		intent.putExtra("phone", phone);
		// 设置结果
		// 第一个参数请求的code
		setResult(Activity.RESULT_OK, intent);
		// 这一句必须要有，即将当前界面结束，把自己杀死，这样才能向上一个界面返回数据
		finish();
	}

	/**
	 * 显示字母
	 * 
	 * @param letter
	 */
	protected void showLetter(String letter) {
		tv_center.setVisibility(View.VISIBLE);
		tv_center.setText(letter);
		bar.setBackgroundColor(Color.rgb(191, 191, 191));

		mHandler.removeCallbacksAndMessages(null);
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				tv_center.setVisibility(View.GONE);
				bar.setBackgroundColor(Color.TRANSPARENT);
			}
		}, 250);

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<ContactInfo2> filterDateList = new ArrayList<ContactInfo2>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = list2;
		} else {
			filterDateList.clear();
			for (ContactInfo2 contactinfo : list2) {
				String name = contactinfo.name;
				if (name.indexOf(filterStr.toString()) != -1
						|| PinyinUtils.getPinyin(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(contactinfo);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList);
		adapter.updateListView(filterDateList);
	}
	
	private class ContactAdapter extends CommonAdapter<ContactInfo2> {

		public ContactAdapter(Context context, int layoutId,
				List<ContactInfo2> datas) {
			super(context, layoutId, datas);
		}
		public void updateListView(List<ContactInfo2> list) {
			mDatas = list;
			notifyDataSetChanged();
		}

		@Override
		public void convert(ViewHolder holder, ContactInfo2 contactInfo) {
			int position = holder.getPos();
			String str = null;
			String currentLetter = contactInfo.pinyin.charAt(0) + "";
			// 根据上一个首字母,决定当前是否显示字母
			if (position == 0) {
				str = currentLetter;
			} else {
				// 上一个人的拼音的首字母
				String preLetter = mDatas.get(position-1).pinyin.charAt(0)+ "";
				if (!TextUtils.equals(preLetter, currentLetter)) {
					str = currentLetter;
				}
			}
			holder.setVisible(R.id.tv_index, str == null ? false : true);
			holder.setText(R.id.tv_index, currentLetter);
			Bitmap bitmap = ContactInfoParser2.getBitmap(mContext, contactInfo.id);
			// 判断当前的bitmap 是否为null。如果为null。那么设置默认的图片
			if (null == bitmap) {
				holder.setImageResource(R.id.icon, R.drawable.contact2);
			} else {
				// 如果不为null。那么直接设置查询出来的图片
				holder.setImageBitmap(R.id.icon, bitmap);
				
			}
			holder.setText(R.id.tv_name, contactInfo.name);
			holder.setText(R.id.tv_number, contactInfo.phone);
		}
	}
}
